# coding: utf-8
import json
from pathlib import Path
from typing import Union

from .setting import HISTORY_FILE


class History:
    """
    历史文件读写
    """

    def __init__(self):
        history_str = HISTORY_FILE.read_text(encoding='utf-8')
        if not history_str:
            self.history = []
        else:
            self.history = json.loads(history_str)

    def add(self, text: str, source: Union[str, Path]):
        if isinstance(source, str):
            source = Path(source)
        self.history.append(
            {
                'name': source.name, 'source': source.as_posix(),
                'text': text[:100],
                'vtt': source.with_suffix('.vtt').as_posix(),
                'srt': source.with_suffix('.srt').as_posix()
            }
        )
        self.save()

    def remove(self, source: Union[str, Path]):
        if isinstance(source, str):
            source = Path(source)
        for item in self.history:
            if item['source'] == source.as_posix():
                self.history.remove(item)
                self.save()
                break

    def save(self):
        HISTORY_FILE.write_text(json.dumps(self.history, ensure_ascii=False, indent=4), encoding='utf-8')

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.save()
